<template>
  <!-- 列表 -->
  <ContentWrap>
    <el-button
      type="primary"
      plain
      @click="openForm('create')"
      v-hasPermi="['mes:base-work-shop:create']"
    >
      <Icon icon="ep:plus" class="mr-5px"/>
      新增
    </el-button>
    <el-table
      v-loading="loading"
      :data="list"
      :stripe="true"
      :show-overflow-tooltip="true"
      @current-change="handleCurrentChange"
    >
      <!--      <el-table-column label="生产区域ID" align="center" prop="id" />-->
      <el-table-column fixed label="区域名称" align="center" prop="machineArea" min-width="100"/>
      <el-table-column label="区域编码" align="center" prop="machineAreaCode"/>
      <el-table-column label="区域状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.MES_COMMON_STATUS" :value="scope.row.status+''"/>
        </template>
      </el-table-column>
      <el-table-column label="PLC编号" align="center" prop="plcId"/>
      <el-table-column label="显示顺序" align="center" prop="orderNo"/>
      <el-table-column label="区域用途" align="center" prop="machineAreaUse"/>
      <el-table-column label="备注信息" align="center" prop="note"/>
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column
        label="更新时间"
        align="center"
        prop="updateTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column label="操作" align="center" min-width="150px">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="openForm('update', scope.row.id)"
            v-hasPermi="['mes:base-work-shop:update']"
          >
            编辑
          </el-button>
          <el-button
            link
            type="danger"
            @click="handleDelete(scope.row.id)"
            v-hasPermi="['mes:base-work-shop:delete']"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      :page-sizes="[5, 10, 15, 20]"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>
  <!-- 表单弹窗：添加/修改 -->
  <BaseMachineAreaForm ref="formRef" @success="getList"/>

</template>
<script setup lang="ts">
import {dateFormatter} from '@/utils/formatTime'
import {BaseMachineAreaVO, BaseWorkShopApi} from '@/api/mes/baseworkshop'
import BaseMachineAreaForm from './BaseMachineAreaForm.vue'
import {DICT_TYPE} from "@/utils/dict";
import {clone} from "@/utils/tools"
import bus from "@/utils/eventBus"

const {t} = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const props = defineProps<{
  workShopId?: number // 所属车间ID（主表的关联字段）
}>()
const loading = ref(false) // 列表的加载中
const list = ref([]) // 列表的数据
const total = ref(0) // 列表的总页数
let queryParams = reactive({
  pageNo: 1,
  pageSize: 5,
  workShopId: undefined as unknown
})
const queryParamsModel = reactive({
  pageNo: 1,
  pageSize: 5,
  workShopId: undefined as unknown
})

/** 监听主表的关联字段的变化，加载对应的子表数据 */
watch(
  () => props.workShopId,
  (val: number) => {
    if (!val) {
      return
    }
    queryParams.workShopId = val
    handleQuery()
  },
  {immediate: true, deep: true}
)

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await BaseWorkShopApi.getBaseMachineAreaPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}


/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = async (type: string, id?: number) => {
  let list = await BaseWorkShopApi.getSimpleWorkShopList()
  if (list.length === 0) {
    message.error('请添加车间信息！')
    return
  }
  formRef.value.open(type, id, props.workShopId, list)
}


/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await BaseWorkShopApi.deleteBaseMachineArea(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {
  }
}

/** 选中行操作 */
const currentRow = ref({}) // 选中行
const handleCurrentChange = (row: BaseMachineAreaVO) => {
  bus.emit("currentRow", row)
  console.log("Row:", currentRow.value)
}

const reset = async (workShopId:string) => {
  queryParams = clone(queryParamsModel)
  queryParams.workShopId=workShopId
  handleQuery()
}

defineExpose({reset})
</script>
